package com.yinhe.music.yhmusic.application;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LongSparseArray;

import com.yinhe.music.common.utils.ScreenUtils;
import com.yinhe.music.yhmusic.base.BaseActivity;
import com.yinhe.music.yhmusic.model.Music;
import com.yinhe.music.yhmusic.utils.Preferences;
import com.yinhe.music.yhmusic.utils.ToastUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class AppCache {
    private Context mContext;
    private  static Map<Long, Music> mMusicSet = new HashMap();
    private final List<BaseActivity> mActivityStack = new ArrayList<>();
    private final LongSparseArray<String> mDownloadList = new LongSparseArray<>();
    public static HashMap<String, Bitmap> mBitMapCache =new HashMap<>();

    private AppCache() {

    }

    private static class SingletonHolder {
        private static AppCache sAppCache = new AppCache();
    }

    private static AppCache getInstance() {
        return SingletonHolder.sAppCache;
    }

    public static void init(Context context) {
        if (getContext() != null) return;
        getInstance().onInit(context);
    }

    private void onInit(Context context) {
        mContext = context.getApplicationContext();
        ToastUtils.init(mContext);
        Preferences.init(mContext);
        ScreenUtils.init(mContext);
        CrashHandler.getInstance().init();
    }

    public static Context getContext() {
        return getInstance().mContext;
    }

    public static Map<Long, Music> getMusicList() {
        return mMusicSet;
    }

    public static void addToStack(BaseActivity activity) {
        getInstance().mActivityStack.add(activity);
    }

    public static void removeFromStack(BaseActivity activity) {
        getInstance().mActivityStack.remove(activity);
    }

    public static void clearStack() {
        List<BaseActivity> activityStack = getInstance().mActivityStack;
        for (int i = activityStack.size() - 1; i >= 0; i--) {
            BaseActivity activity = activityStack.get(i);
            activityStack.remove(activity);
            if (!activity.isFinishing()) {
                activity.finish();
            }
        }
    }

    public static LongSparseArray<String> getDownloadList() {
        return getInstance().mDownloadList;
    }
}
